package com.starblink.android.basic.appupdate

import android.content.Intent
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.AppUtils
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.livedata.Event
import com.starblink.basic.log.SKLogger
import com.starblink.rocketreserver.FetchLatestVersionQuery
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * APP更新管理器
 */
object AppUpdateManager {
    val updateInfoLiveData = MutableLiveData<Event<FetchLatestVersionQuery.FetchLatestVersion?>>()
    const val showLog = false
    /**
     * 检查App更新
     */
    fun checkUpdate() {
        CoroutineScope(Dispatchers.IO).launch {
            val response = SkGqlClient.skQuery(
                //平台 1:ios 2:android
                FetchLatestVersionQuery(
                    platform = 2,
                    version = AppUtils.getAppVersionName(),
//                    version = "0.8.0",  //测试用
                )
            )
            if (response?.data != null && response.data!!.fetchLatestVersion != null) {
                //成功获取更新信息
                SKLogger.e(
                    "dss",
                    "成功获取更新信息=" + response.data!!.fetchLatestVersion + ", in ${Thread.currentThread().name}"
                ,showLog)
                updateInfoLiveData.postValue(Event(response.data!!.fetchLatestVersion!!))
            } else {
                //获取更新信息失败
                SKLogger.e("dss", "获取更新信息失败",showLog)
                updateInfoLiveData.postValue(Event(null))
            }
        }
    }

    /**
     * 启动Google Play APP详情页
     */
    fun startGooglePlay() {
        val intent = Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(
                "https://play.google.com/store/apps/details?id=${AppUtils.getAppPackageName()}"
            )
            setPackage("com.android.vending")
            setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        commContext().startActivity(intent)
    }

//    private val gpAppUpdateManager by lazy { AppUpdateManagerFactory.create(commContext()) }
//    const val UPDATE_REQUEST_CODE = 123

//    /**
//     *  GooglePlay应用内强制更新
//     */
//    fun googlePlayInAppForceUpdate(activity: Activity) {
//        gpAppUpdateManager.appUpdateInfo.addOnSuccessListener {
//            if (it.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
//                && it.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
//            ) {
//                SKLogger.e("dss", "启动强制更新")
//                // 启动强制更新
//                gpAppUpdateManager.startUpdateFlowForResult(
//                    it,
//                    AppUpdateType.IMMEDIATE,
//                    this,
//                    UPDATE_REQUEST_CODE
//                )
//            } else {
//                SKLogger.e("dss", "启动强制更新失败$it")
//                // 启动强制更新失败, 跳转至外部Google Play进行更新
//            }
//        }.addOnFailureListener {
//            SKLogger.e("dss", "获取GooglePlay更新信息失败$it")
//            // 获取GooglePlay更新信息失败, 跳转至外部Google Play进行更新
//        }
//    }
}